#include "main.h"

HDC			hDC=NULL;		// Private GDI Device Context
HGLRC		hRC=NULL;		// Permanent Rendering Context
HWND		hWnd=NULL;		// Holds Our Window Handle
HINSTANCE	hInstance;		// Holds The Instance Of The Application

int W_WIDTH = 800;
int W_HEIGHT = 600;

bool	keys[256];			// Array Used For The Keyboard Routine
bool	active=TRUE;		// Window Active Flag Set To TRUE By Default
bool	fullscreen=TRUE;	// Fullscreen Flag Set To Fullscreen Mode By Default
GLfloat movement;
float distance = 24;
float b_size = 24*(((float)W_HEIGHT)/480);//24;
float scale = ((float)W_HEIGHT/480);

//game variables
CSoundSystem soundsystem;
Map map;
Pachead pachead;
Enemy *enemies[MAXENEMY];
CNum cnum;
Info info;
int difficulty = 1;
int numenemy = 0;
int framecount = 0;
int cfps = 0;
int midimusic[NUMMUSIC];
int songnum = 0;
int highscore = 0;
DWORD framerate = 12;
fstream fo;
fstream fi;
int scorecap = 5000;

DWORD mdelay = 0;

bool key = true;
bool pause = false;
DWORD pdelay = 0;

GLfloat rtri = 0.0f;
GLfloat xrot = -50.0f;
GLfloat yrot = 0.0f;
GLfloat zrot = 0.0f;
bool lightsOn = true;

bool follow = false;
bool firstPerson = false;

float dist = 800.0f;

char *mapnames[] =
	{ 
		"map/level1.mpp",
		"map/level2.mpp",
		"map/level3.mpp",
		"map/level4.mpp",
		"map/level5.mpp",
		"map/level6.mpp",
		"map/level7.mpp",
		"map/level8.mpp",
		"map/level9.mpp",
		"map/level10.mpp",
		"map/level11.mpp",
		"map/level12.mpp",
		"map/level13.mpp",
		"map/level14.mpp",
		"map/level15.mpp"
	};	

char *musicfiles[] = 
{
	"music/obsesion.mid",
	"music/raptech.mid",
	"music/cool2.mid",
	"music/veracocha.mid",
	"music/sunlight.mid",
	"music/bomb.mid",
	"music/sphere.mid",
	"music/freedom.mid",
	"music/egytech.mid",
	"music/kevtech.mid"
};

GLvoid ReSizeGLScene(GLsizei width, GLsizei height)		// Resize And Initialize The GL Window
{
	if (height==0)										// Prevent A Divide By Zero By
	{
		height=1;										// Making Height Equal One
	}

	glViewport(0,0,width,height);						// Reset The Current Viewport

	glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix
	glLoadIdentity();									// Reset The Projection Matrix

	// Calculate The Aspect Ratio Of The Window
	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,1,1000.0f);

	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
	glLoadIdentity();									// Reset The Modelview Matrix

	//gluLookAt(-1*(W_WIDTH/2),-1*(W_HEIGHT/2),200,-1*(W_WIDTH/2),-1*(W_HEIGHT/2),0,0,1,0);
}

int InitGL(GLvoid)										// All Setup For OpenGL Goes Here
{
	GLfloat LightAmbient[]= { 1.5f, 1.5f, 1.5f, 1.0f };
	GLfloat LightDiffuse[]= { 0.5f, 0.5f, 0.5f, 1.0f };
	GLfloat LightPosition[]= { 0.0f, 0.0f, 300.0f, 1.0f };

	glEnable(GL_TEXTURE_2D);							// Enable Texture Mapping ( NEW )
	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);				// Black Background
	glClearDepth(1.0f);									// Depth Buffer Setup
	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing
	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations
	
	glBlendFunc(GL_SRC_ALPHA,GL_ONE);
	glEnable(GL_BLEND);					// Set The Blending Function For Translucency
	

	glLightfv(GL_LIGHT0, GL_AMBIENT, LightAmbient);	
	glLightfv(GL_LIGHT0, GL_DIFFUSE, LightDiffuse);
	glLightfv(GL_LIGHT0, GL_POSITION,LightPosition);
	glEnable(GL_LIGHT0);

	glViewport(0,0,W_WIDTH,W_HEIGHT);
	glEnable(GL_LIGHTING);

	//CAMERA
	//glMatrixMode(GL_MODELVIEW); 
	//glLoadIdentity(); 
	//gluLookAt(400,300,100,400,300,0,0,1,0);

	soundsystem.Initialize(hWnd);//direct sound

	cnum.loaddigits();
	info.loadpictures();
	map.loadmaptiles();
	pachead.loadsprites();
	enemies[0]->loadsprites();
	srand(time(0));

	songnum = rand()%NUMMUSIC;
	difficulty = 1;

	return TRUE;										// Initialization Went OK
}

int DrawGLScene(GLvoid)									// Here's Where We Do All The Drawing
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear The Screen And The Depth Buffer

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective (45.0f, 1.0, 1, 1000);
	glOrtho(-1*(W_WIDTH/2),(W_WIDTH/2),-1*(W_HEIGHT/2),(W_HEIGHT/2),0,-1000.0);

	//CAMERA
	glMatrixMode(GL_MODELVIEW); 
	glLoadIdentity();
	
	if(lightsOn)
	{
		glEnable(GL_LIGHTING);
	}
	else
	{
		glDisable(GL_LIGHTING);
	}
	
	if(firstPerson){
		xrot = 0;
		yrot = 0;
		zrot = 0;
		//glEnable(GL_CLIP_PLANE0);
		
		double xLeft = pachead.x;
		double xRight = xLeft + B_SIZE;
		double xMiddle = xLeft + (xRight-xLeft)/2;

		double yBottom = pachead.y;
		double yTop = yBottom + B_SIZE;		
		double yMiddle = yBottom + (yTop - yBottom)/2;
		
		double dist = 250;
		double zTop = 50;
		double zBottom = 0;

		double offset = 2*B_SIZE;

		switch(pachead.direction)
		{
		case RIGHT:
			{
				gluLookAt(xLeft-offset, yMiddle, zTop, xRight+dist, yMiddle, zBottom, 0, 0, 1);
				double eq[] = {1, 0, 0, -xMiddle - offset};
				//glClipPlane(GL_CLIP_PLANE0, eq);
				break;
			}
		case LEFT:
			{
				gluLookAt(xRight+offset, yMiddle, zTop, xLeft-dist, yMiddle, zBottom, 0, 0, 1);
				double eq[] = {-1, 0, 0, xMiddle + offset};
				//glClipPlane(GL_CLIP_PLANE0, eq);
				break;
			}
		case UP:
			{
				gluLookAt(xMiddle, yBottom-offset, zTop, xMiddle, yTop+dist, zBottom, 0, 0, 1);
				double eq[] = {0, 1, 0, -yMiddle - offset};
				//glClipPlane(GL_CLIP_PLANE0, eq);
				break;
			}
		case DOWN:
			{
				gluLookAt(xMiddle, yTop+offset, zTop, xMiddle, yBottom-dist, zBottom, 0, 0, 1);
				double eq[] = {0, -1, 0, yMiddle + offset};
				//glClipPlane(GL_CLIP_PLANE0, eq);
				break;
			}
		};
	}else{
		glDisable(GL_CLIP_PLANE0);
		if(follow)
		{
			gluLookAt(pachead.x,pachead.y,dist,pachead.x,pachead.y,0,0,1,0);
		}
		else
		{
			gluLookAt(0,0,dist,0,0,0,0,1,0);
		}
	}
	
	if(!fullscreen)
		titlescreen();
	else
		game();

	SwapBuffers(hDC);				// Swap Buffers (Double Buffering)
	
	rtri+=0.2f;

	return TRUE;										// Everything Went OK
}

GLvoid KillGLWindow(GLvoid)								// Properly Kill The Window
{
	if (fullscreen)										// Are We In Fullscreen Mode?
	{
		ChangeDisplaySettings(NULL,0);					// If So Switch Back To The Desktop
		ShowCursor(TRUE);								// Show Mouse Pointer
	}

	if (hRC)											// Do We Have A Rendering Context?
	{
		if (!wglMakeCurrent(NULL,NULL))					// Are We Able To Release The DC And RC Contexts?
		{
			MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}

		if (!wglDeleteContext(hRC))						// Are We Able To Delete The RC?
		{
			MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		hRC=NULL;										// Set RC To NULL
	}

	if (hDC && !ReleaseDC(hWnd,hDC))					// Are We Able To Release The DC
	{
		MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hDC=NULL;										// Set DC To NULL
	}

	if (hWnd && !DestroyWindow(hWnd))					// Are We Able To Destroy The Window?
	{
		MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hWnd=NULL;										// Set hWnd To NULL
	}

	if (!UnregisterClass("OpenGL",hInstance))			// Are We Able To Unregister Class
	{
		MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hInstance=NULL;									// Set hInstance To NULL
	}
}

/*	This Code Creates Our OpenGL Window.  Parameters Are:					*
 *	title			- Title To Appear At The Top Of The Window				*
 *	width			- Width Of The GL Window Or Fullscreen Mode				*
 *	height			- Height Of The GL Window Or Fullscreen Mode			*
 *	bits			- Number Of Bits To Use For Color (8/16/24/32)			*
 *	fullscreenflag	- Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE)	*/
 
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
	GLuint		PixelFormat;			// Holds The Results After Searching For A Match
	WNDCLASS	wc;						// Windows Class Structure
	DWORD		dwExStyle;				// Window Extended Style
	DWORD		dwStyle;				// Window Style
	RECT		WindowRect;				// Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;			// Set Left Value To 0
	WindowRect.right=(long)width;		// Set Right Value To Requested Width
	WindowRect.top=(long)0;				// Set Top Value To 0
	WindowRect.bottom=(long)height;		// Set Bottom Value To Requested Height

	fullscreen=fullscreenflag;			// Set The Global Fullscreen Flag

	hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
	wc.lpfnWndProc		= (WNDPROC) WndProc;					// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= hInstance;							// Set The Instance
	wc.hIcon			= LoadIcon(NULL, MAKEINTRESOURCE(IDI_PACHEAD));
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer
	wc.hbrBackground	= NULL;									// No Background Required For GL
	if(fullscreen)
		wc.lpszMenuName		= NULL;								// We Don't Want A Menu
	else
		wc.lpszMenuName		= "MainMenu";
	
	wc.lpszClassName	= "OpenGL";								// Set The Class Name

	if (!RegisterClass(&wc))									// Attempt To Register The Window Class
	{
		MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;											// Return FALSE
	}
	
	if (fullscreen)												// Attempt Fullscreen Mode?
	{
		DEVMODE dmScreenSettings;								// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= width;				// Selected Screen Width
		dmScreenSettings.dmPelsHeight	= height;				// Selected Screen Height
		dmScreenSettings.dmBitsPerPel	= bits;					// Selected Bits Per Pixel
		dmScreenSettings.dmDisplayFrequency = 85;
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
		{
			// If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.
			if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
			{
				fullscreen=FALSE;		// Windowed Mode Selected.  Fullscreen = FALSE
			}
			else
			{
				// Pop Up A Message Box Letting User Know The Program Is Closing.
				MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
				return FALSE;									// Return FALSE
			}
		}
	}

	if (fullscreen)												// Are We Still In Fullscreen Mode?
	{
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style
		dwStyle=WS_POPUP;										// Windows Style
		ShowCursor(FALSE);// Hide Mouse Pointer
		wc.lpszMenuName		= NULL;
	}
	else
	{
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
		dwStyle=WS_OVERLAPPEDWINDOW;							// Windows Style
		wc.lpszMenuName  = "MainMenu";
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size



	// Create The Window
	if (!(hWnd=CreateWindowEx(	dwExStyle,							// Extended Style For The Window
								"OpenGL",							// Class Name
								title,								// Window Title
								dwStyle |							// Defined Window Style
								WS_CLIPSIBLINGS |					// Required Window Style
								WS_CLIPCHILDREN,					// Required Window Style
								0, 0,								// Window Position
								WindowRect.right-WindowRect.left,	// Calculate Window Width
								WindowRect.bottom-WindowRect.top,	// Calculate Window Height
								NULL,								// No Parent Window
								NULL,								// No Menu
								hInstance,							// Instance
								NULL)))								// Dont Pass Anything To WM_CREATE
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		bits,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};
	
	if (!(hDC=GetDC(hWnd)))							// Did We Get A Device Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!SetPixelFormat(hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(hRC=wglCreateContext(hDC)))				// Are We Able To Get A Rendering Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!wglMakeCurrent(hDC,hRC))					// Try To Activate The Rendering Context
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	ShowWindow(hWnd,SW_SHOW);						// Show The Window
	SetForegroundWindow(hWnd);						// Slightly Higher Priority
	SetFocus(hWnd);									// Sets Keyboard Focus To The Window
	ReSizeGLScene(width, height);					// Set Up Our Perspective GL Screen

	if (!InitGL())									// Initialize Our Newly Created GL Window
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	return TRUE;									// Success
}

LRESULT CALLBACK WndProc(	HWND	hWnd,			// Handle For This Window
							UINT	uMsg,			// Message For This Window
							WPARAM	wParam,			// Additional Message Information
							LPARAM	lParam)			// Additional Message Information
{
	switch (uMsg)									// Check For Windows Messages
	{
		case WM_ACTIVATE:							// Watch For Window Activate Message
		{
			if (!HIWORD(wParam))					// Check Minimization State
			{
				active=TRUE;						// Program Is Active
			}
			else
			{
				active=FALSE;						// Program Is No Longer Active
			}

			return 0;								// Return To The Message Loop
		}

		case WM_SYSCOMMAND:							// Intercept System Commands
		{
			switch (wParam)							// Check System Calls
			{
				case SC_SCREENSAVE:					// Screensaver Trying To Start?
				case SC_MONITORPOWER:				// Monitor Trying To Enter Powersave?
				return 0;							// Prevent From Happening
			}
			break;									// Exit
		}

		case WM_CLOSE:								// Did We Receive A Close Message?
		{
			PostQuitMessage(0);						// Send A Quit Message
			return 0;								// Jump Back
		}

		case WM_KEYDOWN:							// Is A Key Being Held Down?
		{

			keys[wParam] = TRUE;					// If So, Mark It As TRUE

			return 0;								// Jump Back
		}

		case WM_KEYUP:								// Has A Key Been Released?
		{
			key = true;
			keys[wParam] = FALSE;					// If So, Mark It As FALSE
			return 0;								// Jump Back
		}

		case WM_SIZE:								// Resize The OpenGL Window
		{
			ReSizeGLScene(LOWORD(lParam),HIWORD(lParam));  // LoWord=Width, HiWord=Height
			return 0;								// Jump Back
		}
		case WM_COMMAND:
			{
				switch(LOWORD(wParam))
				{
					case ID_GAME_EXIT:SendMessage(hWnd,WM_CLOSE,0,0);break;
					case ID_GAME_PLAY:  
						{
							KillGLWindow();						// Kill Our Current Window
							fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
							// Recreate Our OpenGL Window
							if (!CreateGLWindow("Dyger's Pachead 2",W_WIDTH,W_HEIGHT,16,fullscreen))
							{
								return 0;						// Quit If Window Was Not Created
							}
							DMusic_Play(midimusic[songnum]);
							pachead.level = 1;
							pachead.lives = 9;
							pachead.score = 0;
							map.loadmap(mapnames[0]);
						};break;
					case ID_GAME_CONTROLS:
						MessageBox(NULL,"- Arrows Move Pachead \n- Pg-up / Pg-dwn Changes Music \n- K Suicide \n- R restarts level \n- P pauses game"
										,"Pachead Controls",MB_OK | MB_ICONINFORMATION);
						break;
					case ID_GAME_CUSTOMMAP: loadcustom();break;
					case ID_GAME_ABOUT:
						MessageBox(NULL,"Pachead beta 2.0 \n\nCreated by: \nDerrall Heath"
										,"About Pachead",MB_OK | MB_ICONINFORMATION);

					case ID_CONFIG_640X480:
						{ 
							W_WIDTH = 640; W_HEIGHT = 480; 
							b_size = 24*(((float)W_HEIGHT)/480); scale = ((float)W_HEIGHT/480); 
						}break;
					case ID_CONFIG_800X600:
						{ 
							W_WIDTH = 800; W_HEIGHT = 600; 
							b_size = 24*(((float)W_HEIGHT)/480); scale = ((float)W_HEIGHT/480); 
						}break;
					case ID_CONFIG_1600X1200:
						{ 
							W_WIDTH = 1600; W_HEIGHT = 1200; 
							b_size = 24*(((float)W_HEIGHT)/480); scale = ((float)W_HEIGHT/480); 
						}break;
				};
			}break;
	};

	// Pass All Unhandled Messages To DefWindowProc
	return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	
	fullscreen=FALSE;							// Windowed Mode
	

	// Create Our OpenGL Window
	if (!CreateGLWindow("Dyger's Pachead 2",W_WIDTH,W_HEIGHT,16,fullscreen))
	{
		return 0;									// Quit If Window Was Not Created
	}

	
	DMusic_Init();

	for(int index = 0; index < NUMMUSIC; index++)
	{
		midimusic[index] = DMusic_Load_MIDI(musicfiles[index]);
	}

	fi.open("highscore.dat", ios::in);
	fi >>highscore;
	fi.close();


	timeBeginPeriod(1);
	while(!done)									// Loop That Runs While done=FALSE
	{
		static DWORD timer; //used to check the current time
		//used to determine the time elapsed
		static int diff;

		timer = timeGetTime();
		
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if (active)								// Program Active?
			{
				if (keys[VK_ESCAPE])				// Was ESC Pressed?
				{
					if(!fullscreen)
						done=TRUE;						// ESC Signalled A Quit
					else
					{
						DMusic_Stop(midimusic[songnum]);
						keys[VK_ESCAPE] = false;
						KillGLWindow();						// Kill Our Current Window
						fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
						// Recreate Our OpenGL Window
						if (!CreateGLWindow("Dyger's Pachead 2",W_WIDTH,W_HEIGHT,16,fullscreen))
						{
							return 0;						// Quit If Window Was Not Created
						}
					}

				}
				else								// Not Time To Quit, Update Screen
				{
					DrawGLScene();					// Draw The Scene
			
				}
			}

			if (keys[VK_F1])						// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;					// If So Make Key FALSE
				KillGLWindow();						// Kill Our Current Window
				fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
				// Recreate Our OpenGL Window
				if (!CreateGLWindow("Dyger's Pachead 2",W_WIDTH,W_HEIGHT,16,fullscreen))
				{
					return 0;						// Quit If Window Was Not Created
				}
			}
		}
		
		if(difficulty > 2)
			framerate = 10;
		else
			framerate = 12;

		do//lock frame rate
		{
			diff = timeGetTime() - timer;
		}while(diff < framerate); 
		
		if(diff!=0)
			cfps = 1000/diff;
		
		//framecount for animation
		framecount++;
		if(framecount == 2000)
			framecount = 0;

	}

	// Shutdown
	shutdown();
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}

void shutdown()
{
	fo.open("highscore.dat", ios::out);
	
	fo <<highscore;
	
	fo.close();

//	outfile.open("score.dat", ios::out);//save the highscore
	//outfile <<highscore;
	//outfile.close();


	for(int loop = 0; loop < numenemy; loop++)
	{
		delete enemies[loop];
	}

	
	DMusic_Delete_All_MIDI();
	DMusic_Shutdown();
}

////////////////////////////////////////////////////////////////////////////////////////////
//Load Texture Function!
////////////////////////////////////////////////////////////////////////////////////////////

AUX_RGBImageRec *LoadBMP(char *Filename)				// Loads A Bitmap Image
{
	FILE *File=NULL;									// File Handle

	if (!Filename)										// Make Sure A Filename Was Given
	{
		return NULL;									// If Not Return NULL
	}

	File=fopen(Filename,"r");							// Check To See If The File Exists

	if (File)											// Does The File Exist?
	{

		fclose(File);									// Close The Handle
		return auxDIBImageLoad(Filename);				// Load The Bitmap And Return A Pointer
	}

	return NULL;										// If Load Failed Return NULL
}

GLuint LoadGLTextures(char *filename)	// Load Bitmaps And Convert To Textures
{
	int Status=FALSE;                    // Status Indicator
	
	GLuint texture[1];
	
	AUX_RGBImageRec *TextureImage[1];					// Create Storage Space For The Texture

	memset(TextureImage,0,sizeof(void *)*1);           	// Set The Pointer To NULL

	// Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit
	if (TextureImage[0]=LoadBMP(filename))
	{
		Status=TRUE;									// Set The Status To TRUE

		glGenTextures(1, &texture[0]);					// Create The Texture

		// Typical Texture Generation Using Data From The Bitmap
		glBindTexture(GL_TEXTURE_2D, texture[0]);
		glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	}

	if (TextureImage[0])									// If Texture Exists
	{
		if (TextureImage[0]->data)							// If Texture Image Exists
		{
			free(TextureImage[0]->data);					// Free The Texture Image Memory
		}

		free(TextureImage[0]);								// Free The Image Structure
	}
	
	return texture[0];										// Return The Status
}

/*****************************************************************************************
Function where the game is run
*****************************************************************************************/

void game()
{
	if(DMusic_Status_MIDI(midimusic[songnum]) != MIDI_PLAYING && (timeGetTime() - mdelay) >= 8000)
	{
		songnum++;
		if(songnum >= NUMMUSIC)
			songnum = 0;
		DMusic_Play(midimusic[songnum]);
		mdelay = timeGetTime();
	}

	if(keys[VK_NEXT] && (timeGetTime()-mdelay) > 1000)
	{
		DMusic_Stop(midimusic[songnum]);
		songnum--;
		if(songnum < 0)
			songnum = (NUMMUSIC-1);
		DMusic_Play(midimusic[songnum]);
		mdelay = timeGetTime();

	}
	if(keys[VK_PRIOR] && (timeGetTime()-mdelay) > 1000)
	{
		DMusic_Stop(midimusic[songnum]);
		songnum++;
		if(songnum >= NUMMUSIC)
			songnum = 0;
		DMusic_Play(midimusic[songnum]);
		mdelay = timeGetTime();

	}
	
	if(keys['1'])
	{
		follow = false;
		firstPerson = false;
	}
	if(keys['2'])
	{
		follow = true;
		firstPerson = false;
	}
	if(keys['3']){
		firstPerson = true;
		follow = false;
	}
	if(keys['4'])
	{
		follow = false;
		firstPerson = false;
		rtri = 0.0f;
		xrot = -50.0f;
		yrot = 0.0f;
		zrot = 0.0f;
		lightsOn = true;
		dist = 800.0f;
	}
	if(keys['C'])
	{
		dist -= 4.0f;
	}
	if(keys['V'])
	{
		dist += 4.0f;
	}

	if(keys['Q'])
	{
		lightsOn = false;
	}
	if(keys['W'])
	{
		lightsOn = true;
	}

	if(keys['U'])
	{
		xrot += 1.0f;
	}
	if(keys['J'])
	{
		xrot -= 1.0f;
	}
	if(keys['I'])
	{
		yrot += 1.0f;
	}
	if(keys['K'])
	{
		yrot -= 1.0f;
	}
	if(keys['O'])
	{
		zrot += 1.0f;
	}
	if(keys['L'])
	{
		zrot -= 1.0f;
	}

	glRotatef(xrot,1.0f,0.0f,0.0f);
	glRotatef(yrot,0.0f,1.0f,0.0f);
	glRotatef(zrot,0.0f,0.0f,1.0f);

	map.drawmap();

	for(int loop = 0; loop < numenemy; loop++)
	{
		enemies[loop]->drawenemy();
		if(!pause)
		{
			enemies[loop]->ai();
			enemies[loop]->collision();
		}
	}
	
	pachead.drawpachead();

	if(!pause)
		pachead.input();

	glDisable(GL_DEPTH_TEST);
	info.drawinfo();

	cnum.drawnumber(cfps, 560*scale-(W_WIDTH/2), 24*scale-(W_HEIGHT/2));//temp
	glEnable(GL_DEPTH_TEST);

	if(keys['X']) //k kills yourself
		pachead.death();
	
	if(keys['R'] && pachead.level != 100)  //restart the level
	{
		for(int loop = 0; loop < numenemy; loop++)
		{
			delete enemies[loop];
		}

		map.loadmap(mapnames[pachead.level-1]);
	}

	if(keys['P'] && (timeGetTime()-pdelay) > 1000)
	{
		pdelay = timeGetTime();
		if(pause)
			pause = false;
		else
			pause = true;
	}


	if(map.pacnum <= 0 || keys['A'] || keys['S'] )//skip levels and clean up each
	{
		if(keys['A'])
		{
			keys['A'] = false;
			pachead.level--;
		}
		if(keys['S'])
		{
			keys['S'] = false;
			pachead.level++;
		}
		if(map.pacnum <= 0)
			pachead.level++;

		if(pachead.level > NUMLEVEL && pachead.level != 100)
		{
			pachead.lives++;
			pachead.score += 2000;
			if(pachead.level < 100)
				difficulty++;
			pachead.level = 1;
			
			if(difficulty == 2)
				pachead.loaddyger();
		}

		if(pachead.level < 1)
			pachead.level = NUMLEVEL;
		
		for(int loop = 0; loop < numenemy; loop++)
		{
			delete enemies[loop];
		}

		map.loadmap(mapnames[pachead.level-1]);
	}

	if(pachead.score > scorecap)
	{
		pachead.lives++;
		scorecap *= 2;
		soundsystem.PlaySound(pachead.sounds[EATGHOST]);
	}

	if(pachead.lives < 0)
	{
		pachead.level = 1;
		pachead.lives = 9;
		pachead.score = 0;
		difficulty = 1;
		pachead.loadsprites();
		
		for(int loop = 0; loop < numenemy; loop++)
		{
			delete enemies[loop];
		}

		info.gameover();

		map.loadmap(mapnames[pachead.level-1]);
	}

}


void titlescreen()
{
	//glTranslatef(-400,-300,0.0f);
	glRotatef(rtri,0.0f,1.0f,0.0f);
	//glTranslatef(400,300,0.0f);

	glBindTexture(GL_TEXTURE_2D,info.pictures[0]); //pachead title

		glBegin(GL_QUADS); //draw the tiles
			glTexCoord2f(0.0f, 0.0f); glVertex3f(0-(W_WIDTH/2), 335*scale-(W_HEIGHT/2),  0.0f);	// Bottom Left Of The Texture and Quad
			glTexCoord2f(1.0f, 0.0f); glVertex3f( 640*scale-(W_WIDTH/2), 335*scale-(W_HEIGHT/2),  0.0f);	// Bottom Right Of The Texture and Quad
			glTexCoord2f(1.0f, 1.0f); glVertex3f( 640*scale-(W_WIDTH/2),  (335+128)*scale-(W_HEIGHT/2),  0.0f);	// Top Right Of The Texture and Quad
			glTexCoord2f(0.0f, 1.0f); glVertex3f(0-(W_WIDTH/2),  (335+128)*scale-(W_HEIGHT/2),  0.0f);	// Top Left Of The Texture and Quad
		glEnd();

//glLoadIdentity();


	glBindTexture(GL_TEXTURE_2D, enemies[0]->attacksprites[DOWN][0]);

	//glColor3f(ENEMYBLUE);
	/*
	glBegin(GL_QUADS); //draw the tiles
		glTexCoord2f(0.0f, 0.0f); glVertex3f(128*scale-(W_WIDTH/2), 200*scale-(W_HEIGHT/2),  0.0f);	// Bottom Left Of The Texture and Quad
		glTexCoord2f(1.0f, 0.0f); glVertex3f( (128+110)*scale-(W_WIDTH/2), 200*scale-(W_HEIGHT/2),  0.0f);	// Bottom Right Of The Texture and Quad
		glTexCoord2f(1.0f, 1.0f); glVertex3f( (128+110)*scale-(W_WIDTH/2),  (200+110)*scale-(W_HEIGHT/2),  0.0f);	// Top Right Of The Texture and Quad
		glTexCoord2f(0.0f, 1.0f); glVertex3f(128*scale-(W_WIDTH/2),  (200+110)*scale-(W_HEIGHT/2),  0.0f);	// Top Left Of The Texture and Quad
	glEnd();
	*/

	GLUquadric * sphere = gluNewQuadric();
	gluQuadricTexture(sphere, true);

	glPushMatrix();
	glTranslated(120*scale-(W_WIDTH/2), 200*scale-(W_HEIGHT/2),  0.0f);
	
	glRotated(90, -1, 0, 0);
	glRotated(90, 0, 0, 1);
	gluSphere(sphere, W_WIDTH/16, 75, 75);

	glPopMatrix();

	gluDeleteQuadric(sphere);
	

	glBindTexture(GL_TEXTURE_2D, pachead.sprites[DOWN][0]);

	if(difficulty > 1)
		glColor3f(WHITE);
	else
		glColor3f(PACGREEN);

	/*
	glBegin(GL_QUADS); //draw the tiles
		glTexCoord2f(0.0f, 0.0f); glVertex3f(192*scale-(W_WIDTH/2), 136*scale-(W_HEIGHT/2),  0.0f);	// Bottom Left Of The Texture and Quad
		glTexCoord2f(1.0f, 0.0f); glVertex3f( (192+140)*scale-(W_WIDTH/2), 136*scale-(W_HEIGHT/2),  0.0f);	// Bottom Right Of The Texture and Quad
		glTexCoord2f(1.0f, 1.0f); glVertex3f( (192+140)*scale-(W_WIDTH/2),  (136+140)*scale-(W_HEIGHT/2),  0.0f);	// Top Right Of The Texture and Quad
		glTexCoord2f(0.0f, 1.0f); glVertex3f(192*scale-(W_WIDTH/2),  (136+140)*scale-(W_HEIGHT/2),  0.0f);	// Top Left Of The Texture and Quad
	glEnd();
	*/
	sphere = gluNewQuadric();
	gluQuadricTexture(sphere, true);

	glPushMatrix();
	glTranslated((192+70)*scale-(W_WIDTH/2), (136+70)*scale-(W_HEIGHT/2),  0.0f);
	
	glRotated(90, -1, 0, 0);
	glRotated(90, 0, 0, 1);
	gluSphere(sphere, W_WIDTH/16, 75, 75);
	glRotated(-90, -1, 0, 0);
	glRotated(-90, 0, 0, 1);

	gluDeleteQuadric(sphere);


	glColor3f(WHITE);

	glBindTexture(GL_TEXTURE_2D, map.maptiles[5][0]);

	sphere = gluNewQuadric();
	gluQuadricTexture(sphere, true);
	
	glTranslated(W_WIDTH/32, 0,  W_WIDTH/8);
	gluSphere(sphere, W_WIDTH/45, 30, 30);
	
	glTranslated(0, 0,  W_WIDTH/8);
	gluSphere(sphere, W_WIDTH/45, 30, 30);
	
	glTranslated(0, 0,  W_WIDTH/8);
	gluSphere(sphere, W_WIDTH/45, 30, 30);
	glPopMatrix();
	
	gluDeleteQuadric(sphere);
/*
	glBegin(GL_QUADS); //draw the tile

		glTexCoord2f(0.0f, 0.0f); glVertex3f(228*scale-(W_WIDTH/2), 136*scale-(W_HEIGHT/2),  0.0f);	// Bottom Left Of The Texture and Quad
		glTexCoord2f(1.0f, 0.0f); glVertex3f( (228+64)*scale-(W_WIDTH/2), 136*scale-(W_HEIGHT/2),  0.0f);	// Bottom Right Of The Texture and Quad
		glTexCoord2f(1.0f, 1.0f); glVertex3f( (228+64)*scale-(W_WIDTH/2),  (136+64)*scale-(W_HEIGHT/2),  0.0f);	// Top Right Of The Texture and Quad
		glTexCoord2f(0.0f, 1.0f); glVertex3f(228*scale-(W_WIDTH/2),  (136+64)*scale-(W_HEIGHT/2),  0.0f);	// Top Left Of The Texture and Quad

	glEnd();


	glBegin(GL_QUADS); //draw the tile

		glTexCoord2f(0.0f, 0.0f); glVertex3f(260*scale-(W_WIDTH/2), 80*scale-(W_HEIGHT/2),  0.0f);	// Bottom Left Of The Texture and Quad
		glTexCoord2f(1.0f, 0.0f); glVertex3f( (260+88)*scale-(W_WIDTH/2), 80*scale-(W_HEIGHT/2),  0.0f);	// Bottom Right Of The Texture and Quad
		glTexCoord2f(1.0f, 1.0f); glVertex3f( (260+88)*scale-(W_WIDTH/2),  (80+88)*scale-(W_HEIGHT/2),  0.0f);	// Top Right Of The Texture and Quad
		glTexCoord2f(0.0f, 1.0f); glVertex3f(260*scale-(W_WIDTH/2),  (80+88)*scale-(W_HEIGHT/2),  0.0f);	// Top Left Of The Texture and Quad

	glEnd();	

	glBegin(GL_QUADS); //draw the tile

		glTexCoord2f(0.0f, 0.0f); glVertex3f(310*scale-(W_WIDTH/2), 0-(W_HEIGHT/2),  0.0f);	// Bottom Left Of The Texture and Quad
		glTexCoord2f(1.0f, 0.0f); glVertex3f( (310+120)*scale-(W_WIDTH/2), 0-(W_HEIGHT/2),  0.0f);	// Bottom Right Of The Texture and Quad
		glTexCoord2f(1.0f, 1.0f); glVertex3f( (310+120)*scale-(W_WIDTH/2),  120*scale-(W_HEIGHT/2),  0.0f);	// Top Right Of The Texture and Quad
		glTexCoord2f(0.0f, 1.0f); glVertex3f(310*scale-(W_WIDTH/2),  120*scale-(W_HEIGHT/2),  0.0f);	// Top Left Of The Texture and Quad

	glEnd();	
*/

	glColor3f(WHITE);
}

void loadcustom()
{

	char curdir[MAX_PATH]; 
	_getcwd(curdir, MAX_PATH);
	
	OPENFILENAME ofn;
	char szFileName[MAX_PATH] = "";

	ZeroMemory(&ofn, sizeof(ofn));

	ofn.lStructSize = sizeof(OPENFILENAME); // SEE NOTE BELOW
	ofn.hwndOwner = hWnd;
	ofn.lpstrFilter = "Map Files (*.mpp)\0*.mpp\0All Files (*.*)\0*.*\0";
	ofn.lpstrFile = szFileName;
	ofn.nMaxFile = MAX_PATH;
	ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
	ofn.lpstrDefExt = "mpp";
	
	

	if(GetOpenFileName(&ofn))
	{
		_chdir(curdir);//change the current directory back to the exe

		KillGLWindow();						// Kill Our Current Window
		fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
							// Recreate Our OpenGL Window
		CreateGLWindow("Dyger's Pachead 2",W_WIDTH,W_HEIGHT,16,fullscreen);
		pachead.level = 100;
		pachead.lives = 9;
		pachead.score = 0;
		map.loadmap(szFileName);
		DMusic_Play(midimusic[songnum]);
	}
	
	
	

}
